package com.nt.train.controller;

import com.nt.train.vo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author hlf
 * @version 1.0
 * @date 2022/8/8 9:23
 */
@Controller
@RequestMapping("/spring")
public class MySpringController {

    @RequestMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("name", "张三");
        model.addAttribute("age", "30");
        return "hello";
    }

    @GetMapping("/testIndex")
    public String index(Model model){
//       1、model
//      2、 moelAndview
        model.addAttribute("msg","你好，老铁");
       // model.addAttribute("msg","nihao");
        model.addAttribute("f1",true);
        model.addAttribute("d1",new Date());
        model.addAttribute("aa",null);
        return "testIndex";
    }

    @RequestMapping("/testIndex2")
    public ModelAndView testIndex2(HttpServletRequest request,HttpServletResponse response,Model model) {
        ModelAndView mav = new ModelAndView("testIndex");
        mav.addObject("msg","你好,老莫");
        // model.addAttribute("msg","nihao");
        mav.addObject("f1",true);
        mav.addObject("d1",new Date());
        mav.addObject("aa",null);
        request.setAttribute("testRequest","testRequest");
        request.getSession().setAttribute("sessionId","test is session");
        //  application对象 ServletContext被称为应用上下文/servlet上下文
        request.getServletContext().setAttribute("applicationCode","900");

        Cookie cookie=new Cookie("cookName","瓜田李下3");
        cookie.setMaxAge(60);
        response.addCookie(cookie);
        return mav;
    }

    @RequestMapping("/testIndex3")
    public ModelAndView testIndex2(HttpServletRequest request, ModelAndView mav) {
        mav.setViewName("testIndex");
        mav.addObject("msg","你好,老莫");
        // model.addAttribute("msg","nihao");
        mav.addObject("f1",true);
        mav.addObject("d1",new Date());
        mav.addObject("aa",null);
        request.setAttribute("bb","testRequest");
        request.getSession().setAttribute("sessionId","test is session");
        return mav;
    }


    @GetMapping("/testList")
    public String testList(Model model){
        List<User>users=new ArrayList<>();
        for (int i = 0; i <10 ; i++) {
            User user=new User();
            user.setId((long) i);
            user.setUserName("小羊"+i+"号");
            user.setAddress("翻斗大街" + i+"号");
            users.add(user);
        }
        model.addAttribute("users",users);
        return "testList";
    }



    @RequestMapping("/article/{id}")
    public ModelAndView getArticle(@PathVariable("id") Integer id) {
        ModelAndView mav = new ModelAndView("article/show");
        mav.addObject("article", id);
        return mav;
    }

    @RequestMapping("/addUser")
    public ModelAndView addUser(String userName) {
        ModelAndView mav = new ModelAndView("article/show");
        mav.addObject("article", userName);
        return mav;
    }

    @RequestMapping("/addUsers")
    public ModelAndView addUsers(User user) {
        ModelAndView mav = new ModelAndView("article/show");
        mav.addObject("article", user);
        return mav;
    }

    @RequestMapping("addUserh")
    public ModelAndView addUserh(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("article/show");
        User user = new User();
        user.setName(request.getParameter("name"));
        user.setAge(Integer.parseInt(request.getParameter("age")));
        mav.addObject("article", user);
        return mav;
    }

    @RequestMapping("addUserr")
    public ModelAndView addUserh(@RequestParam(value = "name", required = false) String name) {
        ModelAndView mav = new ModelAndView("article/show");
        mav.addObject("article", name);
        return mav;
    }

    @RequestMapping("saveUser")
    public String saveUser(@RequestBody List<User> users) {
        return users.toString();
    }



    /** ViewResolver请求转发  start  */
    @RequestMapping(value="/testredirect",method = { RequestMethod.POST})
    public  String testredirect(HttpServletResponse response){
        return "forward:/index";
    }

    //带参数
    @RequestMapping(value="/testredirect2",method = { RequestMethod.POST })
    public  String testredirect(HttpServletRequest request){
        request.setAttribute("username", "51gjie");   //把username参数传递到request中
        return "forward:/user/index";
    }

    /** ViewResolver请求转发  end  */

    /** ModelAndView请求转发  start*/
    @RequestMapping(value="/restredirect3",method = { RequestMethod.POST })
    public  ModelAndView restredirect(String userName){
        //默认forward，可以不用写
        ModelAndView  model = new ModelAndView("forward:/main/index");
        return model;
    }

    //带参数转发
    @RequestMapping(value="/toredirect4",method = { RequestMethod.POST, RequestMethod.GET })
    public  ModelAndView toredirect(String userName){
        ModelAndView  model = new ModelAndView("/user/userinfo");
        model.addObject("userName", userName);  //把userName参数带入到controller的RedirectAttributes
        return model;
    }

    /**
     * //带参数转发
     * 控制器方法返回值是ModelAndView实现转发forward
     * 语法：mv.setViewName("forward:视图完整路径")
     * forward特点：不和视图解析器一同工作的，就当项目中没有视图解析器
     */
    @RequestMapping(value = "/forward.do")
    public ModelAndView doforward(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","在ModelAddView中处理了doforward.do的请求");
        mv.addObject("fun","执行了dosome的方法");
        //请求转发1
        mv.setViewName("forward:WEB-INF/view/show.jsp");
        return  mv;
    }
    /*
    //带参数转发
    * 处理器方法返回MadelAndView,实现转发forword
    * 语法：setViewName("forward:视图文件的完整路径")
    * forward特点：不和视图解析器一同使用，就当项目中没有视图解析器
    * */
    @RequestMapping(value = "/queryEmps.do")
    @ResponseBody
    public ModelAndView queryEmps(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","张三");
        mv.setViewName("forward:/WEB-INF/jsp/show.jsp");
        return mv;
    }


    /**
     * 当控制器方法返回modelAndview实现重定向  语法： mv.setViewName("redirect：视图完整路径")
     *  redirect特点：不和视图解析器一同工作，相当于项目中没有视图解析器
     *  框架提供重定向的功能   (不能访问WEB-INF)
     *      1.框架可以实现两次请求之前的数据传递，把第一次请求中的model里面简单类型的数据转换中成为字符串
     *      附加到目标页面的后面，做get传递参数。也可以在目标页面中获取参数值使用
     *      2.在目标页面中，可以使用${param.参数名} 获取参数的值
     */
    @RequestMapping("/redirect.do")
    public ModelAndView doRedirect(String name,Integer age){
        System.out.println("在ModelAddView中处理了doRedirect.do的请求");
        ModelAndView mv=new ModelAndView();
        mv.addObject("name",name);
        mv.addObject("age",age);
        //请求转发1
        mv.setViewName("redirect:/other.jsp");
        return  mv;
    }

    /*
    * 处理器方法返回ModelAndView，实现重定向redirect
    * 语法:setViewName("redirect:视图完整路径")
    * redirect特点: 不和视图解析器一同使用，就当项目中没有视图解析器
    *
    * 框架对重定向的操作:
    * 1.框架会把Model中简单类型的数据转为String使用，作为show.jsp的get请求参数使用。目的是在queryEmps.do
    * 和show.jsp两次请求之间传递参数
    *
    * 2.在目标show.jsp页面中，可以使用参数集合对象${param}获取请求参数值
    * ${param.msg}
    *
    * 3.重定向无法访问WEB-INF的资源
    * */
    @RequestMapping(value = "/queryEmps2.do")
    @ResponseBody
    public ModelAndView queryEmps2(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","张三");
        mv.setViewName("redirect:/show.jsp");
        //重定向后，浏览器会发起第二次请求http://localhost:8080/SSM/show.jsp?msg=张三
        return mv;
    }
    /** ModelAndView请求转发  end*/


    /**
     * 请求转发的第一种情况：请求转发经过视图解析器
     前端页面
     <a href="${pageContext.request.contextPath}/forwardMvcView">请求转发经过视图解析器</a>
     */
    @RequestMapping("/forwardMvcView")
    public String forwardMvcView(){
        return "success";
    }

    /**
     * 请求转发的第二种情况：不经过视图解析器
     前端页面
     <a href="${pageContext.request.contextPath}/forwardView">请求转发经过视图解析器</a>
     后台代码(由于不经过视图解析器，所以需要自己拼接前后缀)forward:关键字后面的路径表示不再经过视图解析器
     */
    @RequestMapping("/forwardView")
    public String forwardView(){
        return "forward:/WEB_INF/pages/success.jsp";
    }

    /**
     * 请求转发的第三种情况：请求转发传统的方式——原生Servlet
     前端页面
     <a href="${pageContext.request.contextPath}/forwardCommon">请求转发经过视图解析器</a>
     */
    @RequestMapping("/forwardCommon")
    public void forwardCommon(HttpServletRequest request,HttpServletResponse response){

         //request.getServletDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
    }


}
